package com.hk.Mgr.web.controller;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.hk.Mgr.web.message.FinancialReq;
import com.hk.Mgr.web.message.RequestMsg;
import com.hk.app.utils.ExcelService;
import com.hk.commons.HqlFilter;
import com.hk.commons.ResultCode;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.vo.FinancialDetailMsg;
import com.hk.service.IOrganization_New;
import com.hk.service.impl.StatisticsHelp;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.sys.StatisticsReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.StringHelper;
import com.hk.commons.vo.StatisticsMsg;
import com.hk.service.IOrganization;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IReservation;
import com.hk.service.order.IStatisticsInfo;
import com.hk.service.sys.ISysUser;

import javax.servlet.http.HttpServletResponse;

/**
 * 获取团队统计日报
 * @author jeff
 *
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/StatisticsCtrl")
public class StatisticsCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(StatisticsCtrl.class);

	private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private IOrganization_New orgNewService;

	@Autowired
	private IReservation reservationService;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IOrganization_New organizationService;

	@Autowired
	private StatisticsHelp statisticsHelp;

	@Autowired
	private IStatisticsInfo statisticsService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * @Title: 获取团队交易统计日报
	 * @Description:
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllInfoNum", method = RequestMethod.POST)
	public ResponseBase<List<StatisticsMsg>> getAllInfo(
			@RequestBody StatisticsReq req) {
		String beginDateStr = req.getStartTime();
		String endDateStr = req.getEndTime();
		Long parId = req.getParId();

		Long beginTimeLong = null;
		Long endTimeLong = null;

		try {

			// 添加时间和产品相关的属性
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

			Date beginDate = null;
			Date endDate = null;

			if (StringHelper.isNotEmpty(beginDateStr)) {
				beginDate = format.parse(beginDateStr);
			}

			if (StringHelper.isNotEmpty(endDateStr)) {
				endDate = format.parse(endDateStr);
			}

			if (beginDate != null) {
				beginTimeLong = beginDate.getTime();
			}

			if (endDate != null) {
				endTimeLong = endDate.getTime() + 60 * 60 * 24 * 1000;
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ResponseBase<List<StatisticsMsg>> resp = new ResponseBase<List<StatisticsMsg>>();
		List<StatisticsMsg> statisticsList = getAllInfoMsg(beginTimeLong, endTimeLong, parId);


		Collections.sort(statisticsList);
		/*

		List<StatisticsMsg> statisticsList = new ArrayList<StatisticsMsg>();
		List<StatisticsMsg> orgList = getOrgList(beginDateStr, endDateStr,
				parId);


		for (StatisticsMsg statisticsInfo : orgList) {
			statisticsInfo.setStartTime(beginTimeLong);
			statisticsInfo.setEndTime(endTimeLong);
			statisticsInfo.setParId(parId);

			StatisticsMsg resultInfo = statisticsService
					.getInfo(statisticsInfo);

			statisticsList.add(resultInfo);
			// System.out.println("部门id = " + org.getId() + " orgName = " +
			// org.getName() + "   " + org.getFlag01() );

		}
		*/
		resp.setSize(statisticsList.size());
		resp.setResult(statisticsList);
		resp.setResultCode(StatusCode.SUCCESS.key());
		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/queryFinancialDetail", method = RequestMethod.POST)
	public ResponseBase<List<FinancialDetailMsg>> queryFinancialDetail(@RequestBody FinancialReq request) {
		Integer curPage = request.getCurPage();
		Integer pageSize = request.getPageSize();

		ResponseBase<List<FinancialDetailMsg>> responseBase = new ResponseBase();

		DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		String sql = "select userId, created from t_financial_log where channel = 2";

		if (StringHelper.isNotEmpty(request.getStartTime())) {
			LocalDate startTime = LocalDate.parse(request.getStartTime(), dateFormatter);
			sql += " and created >= " + Timestamp.valueOf(LocalDateTime.of(startTime, LocalTime.of(0, 0))).getTime();
		}

		if (StringHelper.isNotEmpty(request.getEndTime())) {
			LocalDate endTime = LocalDate.parse(request.getEndTime(), dateFormatter);
			sql += " and created <= " + Timestamp.valueOf(LocalDateTime.of(endTime, LocalTime.of(23, 59))).getTime();
		}

		sql += " order by created desc";

		List<Map<String, Object>> results = this.jdbcTemplate.queryForList(sql);

		Set<Long> userIds = new HashSet<>();

		long now = System.currentTimeMillis();

		List<FinancialDetailMsg> financialDetailMsgList = results.parallelStream().map(result -> {
			FinancialDetailMsg financialDetailMsg = new FinancialDetailMsg();
			Long userId = (Long)result.get("userId");
			Long created = (Long)result.get("created");

			if (!userIds.contains(userId)) {
				userIds.add(userId);

				SysUser sysUser = this.sysUserService.findById(userId);
				if (sysUser != null) {
					financialDetailMsg.setName(StringHelper.isBlank(sysUser.getName()) ? "": sysUser.getName());
					financialDetailMsg.setRealName(sysUser.getRealName());

					String userViewSql = "select * from userview where userId = ?";
					List<Map<String, Object>> userViewList = this.jdbcTemplate.queryForList(userViewSql, new Object[] { sysUser.getId() });

					if (userViewList.size() > 0) {
						Map<String, Object> map = userViewList.get(0);
						String userOrgName = (String)map.get("userOrgName");
						Integer isInside = (Integer)map.get("isInside");

						if (StringHelper.isNotEmpty(userOrgName)) {
							financialDetailMsg.setUserOrgName(this.organizationService.getChannelNameByChannelId(sysUser.getChannel()));
							financialDetailMsg.setCompany(userOrgName);

							financialDetailMsg.setJob("");
							if (isInside != null && isInside == 1 && StringHelper.isNotEmpty(userOrgName)) {
								String[] userOrgNameArray = userOrgName.split("-");
								if (userOrgNameArray.length > 0) {
									financialDetailMsg.setJob(userOrgNameArray[userOrgNameArray.length - 1]);
								}
							}

						} else {
							financialDetailMsg.setUserOrgName("");
							financialDetailMsg.setCompany("");
							financialDetailMsg.setJob("");
						}

						LocalDateTime datetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(created), ZoneId.systemDefault());
						financialDetailMsg.setCreated(datetime.format(formatter));
					}
				} else {
					financialDetailMsg.setId(1L);
				}

			} else {
				financialDetailMsg.setId(1L);
			}
			return financialDetailMsg;
		}).filter(financialDetailMsg -> financialDetailMsg.getId() == null).collect(Collectors.toList());
		long timeEnd = System.currentTimeMillis();
		logger.info("time: " + (timeEnd - now));

		Integer size = financialDetailMsgList.size();

		Integer begin = 0;
		Integer end = 0;

		if (size > 0) {
			begin = (curPage - 1) * pageSize;

			if (begin + pageSize < size) {
				end = curPage * pageSize;
			} else {
				end = size;
			}

		}

		financialDetailMsgList = financialDetailMsgList.subList(begin, end);

		responseBase.setResultCode(ResultCode.SUCC.getCode());
		responseBase.setMsg("success");
		responseBase.setResult(financialDetailMsgList);
		responseBase.setSize(financialDetailMsgList.size());

		return responseBase;
	}

	@ResponseBody
	@RequestMapping(value = "/queryFinancialDetailExcel", method = RequestMethod.GET)
	public void queryFinancialDetailExcel(@RequestParam String startTimeStr, String endTimeStr, HttpServletResponse response) {
		DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		String sql = "select userId, created from t_financial_log where channel = 2";

		if (StringHelper.isNotEmpty(startTimeStr)) {
			LocalDate startTime = LocalDate.parse(startTimeStr, dateFormatter);
			sql += " and created >= " + Timestamp.valueOf(LocalDateTime.of(startTime, LocalTime.of(0, 0))).getTime();
		}

		if (StringHelper.isNotEmpty(endTimeStr)) {
			LocalDate endTime = LocalDate.parse(endTimeStr, dateFormatter);
			sql += " and created <= " + Timestamp.valueOf(LocalDateTime.of(endTime, LocalTime.of(23, 59))).getTime();
		}

		sql += " order by created desc";

		List<Map<String, Object>> results = this.jdbcTemplate.queryForList(sql);
		Set<Long> userIds = new HashSet<>();

		List<FinancialDetailMsg> financialDetailMsgList = results.parallelStream().map(result -> {
			FinancialDetailMsg financialDetailMsg = new FinancialDetailMsg();
			Long userId = (Long)result.get("userId");
			Long created = (Long)result.get("created");

			if (!userIds.contains(userId)) {
				userIds.add(userId);

				SysUser sysUser = this.sysUserService.findById(userId);
				if (sysUser != null) {
					financialDetailMsg.setName(StringHelper.isBlank(sysUser.getName()) ? "": sysUser.getName());
					financialDetailMsg.setRealName(sysUser.getRealName());

					String userViewSql = "select * from userview where userId = ?";
					List<Map<String, Object>> userViewList = this.jdbcTemplate.queryForList(userViewSql, new Object[] { sysUser.getId() });

					if (userViewList.size() > 0) {
						Map<String, Object> map = userViewList.get(0);
						String userOrgName = (String)map.get("userOrgName");
						Integer isInside = (Integer)map.get("isInside");

						if (StringHelper.isNotEmpty(userOrgName)) {
							financialDetailMsg.setUserOrgName(this.organizationService.getChannelNameByChannelId(sysUser.getChannel()));
							financialDetailMsg.setCompany(userOrgName);

							financialDetailMsg.setJob("");
							if (isInside != null && isInside == 1 && StringHelper.isNotEmpty(userOrgName)) {
								String[] userOrgNameArray = userOrgName.split("-");
								if (userOrgNameArray.length > 0) {
									financialDetailMsg.setJob(userOrgNameArray[userOrgNameArray.length - 1]);
								}
							}

						} else {
							financialDetailMsg.setUserOrgName("");
							financialDetailMsg.setCompany("");
							financialDetailMsg.setJob("");
						}

						LocalDateTime datetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(created), ZoneId.systemDefault());
						financialDetailMsg.setCreated(datetime.format(formatter));
					}
				} else {
					financialDetailMsg.setId(1L);
				}

			} else {
				financialDetailMsg.setId(1L);
			}
			return financialDetailMsg;
		}).filter(financialDetailMsg -> financialDetailMsg.getId() == null).collect(Collectors.toList());

		List<Map<String, Object>> qryMapList = new ArrayList<>();
		for (FinancialDetailMsg financialDetailMsg: financialDetailMsgList) {
			Map<String, Object> map = new HashMap<>();
//			map.put("id", financialDetailMsg.getId());
			map.put("name", financialDetailMsg.getName());
			map.put("realName", financialDetailMsg.getRealName());
			map.put("userOrgName", financialDetailMsg.getUserOrgName());
			map.put("company", financialDetailMsg.getCompany());
			map.put("job", financialDetailMsg.getJob());
			map.put("created", financialDetailMsg.getCreated());
			qryMapList.add(map);
		}

		LinkedHashMap<String, String> struct = new LinkedHashMap<>();
//		struct.put("id", "序号");
		struct.put("name", "账号");
		struct.put("realName", "姓名");
		struct.put("userOrgName", "渠道");
		struct.put("company", "部门");
		struct.put("job", "职务");
		struct.put("created", "最后使用时间");

		ExcelService excelService = new ExcelService(qryMapList, struct);
		String title = "理财师APP使用记录";
		excelService.exportToStream(response, title);
	}

	public List<StatisticsMsg> getAllInfoMsg(Long  beginTime, Long endTime, Long parId) {
		List<StatisticsMsg> returnList = new ArrayList<StatisticsMsg>();
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("flag01", "1");
		List<Organization> orgList = orgNewService.findByFilter(hqlFilter);

//		for(Organization org : orgList){
//			StatisticsMsg orgStatisticsMsg = statisticsHelp.getStatisticsMsg(org.getId(), beginTime, endTime, parId);
//			returnList.add(orgStatisticsMsg);
//			if(orgNewService.hasVirsualDep(org.getId()) && orgNewService.showVirsualDep(org.getId())){
//				orgStatisticsMsg = statisticsHelp.getVirsualDepStatisticsMsg(org.getId(), beginTime, endTime, parId);
//				returnList.add(orgStatisticsMsg);
//			}
//		}

		returnList = orgList.parallelStream()
					.map(org -> statisticsHelp.getStatisticsMsg(org.getId(), beginTime, endTime, parId))
					.collect(Collectors.toList());

		returnList.addAll(orgList.parallelStream()
				.filter(org -> orgNewService.hasVirsualDep(org.getId()) && orgNewService.showVirsualDep(org.getId()))
				.map(org -> statisticsHelp.getVirsualDepStatisticsMsg(org.getId(), beginTime, endTime, parId))
				.collect(Collectors.toList()));

		return returnList;
	}



	public List<StatisticsMsg> getOrgList(String beginDateStr,
			String endDateStr, Long prodId) {
		List<StatisticsMsg> orgList = new ArrayList<StatisticsMsg>();

		StatisticsMsg org = null;
		// 01 直销广州分公司
		org = new StatisticsMsg("直销渠道一部", "直销广州分公司", "直销广州分公司", "1-2-3-6", 1);
		orgList.add(org);
		// 02 直销重庆分公司
		org = new StatisticsMsg("直销渠道一部", "直销重庆分公司", "直销重庆分公司", "1-2-3-7", 2);
		orgList.add(org);
		// 03 直销上海分公司
		org = new StatisticsMsg("直销渠道一部", "直销上海分公司", "直销上海分公司", "1-2-3-8", 3);
		orgList.add(org);
		// 04 直销直属
		org = new StatisticsMsg("直销渠道一部", "直销一部直属", "直销一部直属", "1-2-3-595", 4);
		orgList.add(org);
		// 05 直销渠道一部合计
		org = new StatisticsMsg("直销渠道一部", "直销一部合计", "小计", "1-2-3", 5);
		orgList.add(org);

		// 06 直销渠道二部合计
		org = new StatisticsMsg("直销渠道二部", "直销二部合计", "小计", "1-33333", 6);
		orgList.add(org);

		// 07 内渠北京分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-北京分公司", "内部渠道一部-北京分公司",
				"1-2-5-127", 7);
		orgList.add(org);
		// 08 内渠广东分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-广东分公司", "内部渠道一部-广东分公司",
				"1-2-5-128", 8);
		orgList.add(org);
		// 09 内渠湖北分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-湖北分公司", "内部渠道一部-湖北分公司",
				"1-2-5-129", 9);
		orgList.add(org);
		// 10 内渠江苏分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-江苏分公司", "内部渠道一部-江苏分公司",
				"1-2-5-130", 10);
		orgList.add(org);
		// 11 内渠辽宁分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-辽宁分公司", "内部渠道一部-辽宁分公司",
				"1-2-5-131", 11);
		orgList.add(org);
		// 12 内渠四川分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-四川分公司", "内部渠道一部-四川分公司",
				"1-2-5-132", 12);
		orgList.add(org);
		// 13 内渠重庆分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-重庆分公司", "内部渠道一部-重庆分公司",
				"1-2-5-451", 13);
		orgList.add(org);
		// 14 内渠湖南分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-湖南分公司", "内部渠道一部-湖南分公司",
				"1-2-5-469", 14);
		orgList.add(org);
		// 15 内渠河南分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-河南分公司", "内部渠道一部-河南分公司",
				"1-2-5-503", 15);
		orgList.add(org);
		
		// 16 内渠河北分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-河北分公司", "内部渠道一部-河北分公司",
				"1-2-5-627", 16);
		orgList.add(org);
		
		// 17 内渠福建分公司
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-福建分公司", "内部渠道一部-福建分公司",
				"1-2-5-740", 17);
		orgList.add(org);

		// 18 内渠一部直属
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部-直属", "内部渠道一部-直属",
				"1-2-5-596", 18);
		orgList.add(org);
		// 19 内渠一部小计
		org = new StatisticsMsg("内部渠道一部", "内部渠道一部合计", "小计", "1-2-5", 19);
		orgList.add(org);

		// 20 内渠安徽分公司
		org = new StatisticsMsg("内部渠道二部", "内部渠道二部-安徽分公司", "内部渠道二部-安徽分公司",
				"1-2-4-133", 20);
		orgList.add(org);
		// 21 内渠重庆分公司
		org = new StatisticsMsg("内部渠道二部", "内部渠道二部-山东分公司", "内部渠道二部-山东分公司",
				"1-2-4-134", 21);
		orgList.add(org);
		
		// 22 内渠湖南分公司
		org = new StatisticsMsg("内部渠道二部", "内部渠道二部-上海分公司", "内部渠道二部-上海分公司",
				"1-2-4-135", 22);
		orgList.add(org);
		
		// 23 内渠浙江分公司
		org = new StatisticsMsg("内部渠道二部", "内部渠道二部-浙江分公司", "内部渠道二部-浙江分公司",
				"1-2-4-136", 23);
		orgList.add(org);

		// 24 内部渠道二部-直属
		org = new StatisticsMsg("内部渠道二部", "内部渠道二部-直属", "内部渠道二部-直属",
				"1-2-4-597", 24);
		orgList.add(org);
		
		// 25 内部渠道二部合计
		org = new StatisticsMsg("内部渠道二部", "内部渠道二部合计", "小计", "1-2-4", 25);
		orgList.add(org);

		// 26 居间渠道部
		org = new StatisticsMsg("居间渠道部", "居间渠道部", "小计", "1-2-423", 26);
		orgList.add(org);
		
		// 27 综合业务部
		org = new StatisticsMsg("综合业务部", "综合业务部", "小计", "1-2-434", 27);
		orgList.add(org);
		
		// 28 无主客户服务部
		org = new StatisticsMsg("无主客户服务部", "无主客户服务部", "小计", "1-88888", 28);
		orgList.add(org);
		
		// 29 直销渠道一部合计
		org = new StatisticsMsg("华康财富", "华康财富", "合计", "1-2", 29);
		orgList.add(org);

		return orgList;

	}

}
